package de.wbh.gwt.form.layouter.gwt.ui.view.widget;

import com.google.common.base.Strings;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class NewFieldPopup extends PopupPanel {

	interface NewFieldPopupUiBinder extends UiBinder<Widget, NewFieldPopup> {
	}

	private static NewFieldPopupUiBinder uiBinder = GWT.create(NewFieldPopupUiBinder.class);

	private final AsyncCallback<String> callback;

	@UiField
	TextBox idTextBox;

	@UiField
	Button okButton;

	public NewFieldPopup(AsyncCallback<String> callback) {
		setWidget(uiBinder.createAndBindUi(this));
		this.callback = callback;
		this.idTextBox.addKeyPressHandler(new KeyPressHandler() {

			@Override
			public void onKeyPress(KeyPressEvent event) {
				String id = NewFieldPopup.this.idTextBox.getText();
				NewFieldPopup.this.okButton.setEnabled(!Strings.isNullOrEmpty(id));
			}
		});
	}

	@UiHandler("cancelButton")
	void onCancelButtonClick(ClickEvent event) {
		this.callback.onFailure(new Exception("Abbruch"));
	}

	@UiHandler("okButton")
	void onOkButtonClick(ClickEvent event) {
		if (!Strings.isNullOrEmpty(this.idTextBox.getText())) {
			this.callback.onSuccess(this.idTextBox.getText());
		}
	}

	@Override
	public void show() {
		super.show();
		this.idTextBox.setText("");
		this.okButton.setEnabled(false);
	}

}
